package java_thinking.unit_21._21_15;

import javax.annotation.concurrent.ThreadSafe;
import java.util.concurrent.atomic.AtomicReference;

/**
 * desc     :
 * dateTime : 2020-06-15 23:09
 *
 * @author wwchen
 */
@ThreadSafe
public class LinkedQueue_1<E> {
    private static class Node<E> {
       private E item;
       private AtomicReference<Node<E>> next;

        public Node(E item, Node<E> next) {
            this.item = item;
            this.next = new AtomicReference<>(next);
        }
    }

    private final Node<E> dumy = new Node<>(null, null);
    private AtomicReference<Node<E>> head = new AtomicReference<>(dumy);
    private AtomicReference<Node<E>> tail = new AtomicReference<>(dumy);

    public boolean put(E item){
        Node<E> newNode = new Node<>(item, null);
        while(true){
            Node<E> curr = tail.get();
            Node<E> next = curr.next.get();
            if (curr == tail.get()){
                if(next != null){
                    tail.compareAndSet(curr,newNode);
                } else {
                    if (curr.next.compareAndSet(null,newNode)){
                        tail.compareAndSet(curr,newNode);
                        return true;
                    }
                }
            }

        }

    }

}
